package com.wzq.animal.fore.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzq.animal.common.Result;
import com.wzq.animal.fore.pojo.News;
import com.wzq.animal.fore.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsService newsService;

    /**
     * 获取新闻
     * @return
     */
    @GetMapping("/getNews")
    public Result getNews(){
        List<News> news = newsService.list();
        return Result.success(news);
    }

    /**
     * 根据 id 获取指定新闻
     * @param id
     * @return
     */
    @GetMapping("/getOne/{id}")
    public Result getOnePieceOfNews(@PathVariable("id") int id){
        News oneNews = newsService.getById(id);
        return Result.success(oneNews);
    }

    @GetMapping("/getPages/{currentPage}/{pageSize}")
    public Result getPages(@PathVariable("currentPage") int currentPage,
                           @PathVariable("pageSize") int pageSize,
                           @RequestParam("titleKeywords") String titleKeywords){
        Page<News> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(titleKeywords)) {
            queryWrapper.like(News::getTitle, titleKeywords);
        }
        newsService.page(page, queryWrapper);
        return Result.success(page);
    }

    @PostMapping("/addOrUpdateNews")
    public Result addOrUpdateNews(@RequestBody News news) {
        newsService.saveOrUpdate(news);
        Integer id = news.getId();
        if(StringUtils.isNotBlank(id.toString())){
            News updatedNews = newsService.getById(id);
            return Result.success(updatedNews);
        }
        return Result.success();
    }

    @DeleteMapping("/delNews/{id}")
    public Result delNews(@PathVariable("id") int id) {
        newsService.removeById(id);
        return Result.success();
    }

    @DeleteMapping("/delNewsBatch")
    public Result delBatch(@RequestBody List<Integer> ids) {
        newsService.removeByIds(ids);
        return Result.success();
    }
}
